package servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import actionForm.CreateContactGroupValidationForm;
import domain.ContactGroup;
import domain.IDAOContactGroup;

public class CreateContactGroupAction extends Action {
	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest request,
			final HttpServletResponse response) {
		if (request.getMethod().equals("POST")) {
			final CreateContactGroupValidationForm lForm=(CreateContactGroupValidationForm)pForm;
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
			IDAOContactGroup daoContactGroup = (IDAOContactGroup) context.getBean("daocontactgroup");
			final ContactGroup lError = daoContactGroup.addContactGroup(lForm.getGroupName());
			if(lError != null){
				request.setAttribute("successMessage", "The contact group has been created.");
				return pMapping.findForward("success");
			} else {
				request.setAttribute("errorMessage", "The contact group could not be created. It may already exist.");
				return pMapping.findForward("error");
			}
		}
		return null;
	}
}